import React from 'react';
import {
  TouchableOpacity,
  View,
  Text,
  ScrollView,
} from 'react-native';

import ToastUtils from '../common/ToastUtils';
import SizeUtils from '../common/SizeUtils';
import TComponent from './TComponent';
import TImageUpLoadOneComponent from './TImageUpLoadOneComponent';

//上传多个图片控件
export default class TImageUpLoadMultiComponent extends TComponent {
  constructor(props) {
    super(props);

    // this.props.onUpdateData

    this.state.updateDataMark = 0;
    // this.props.imageStyle  图片格子宽高 只有width, height生效
    // 保存初始化的图片链接数据
    this._customImageUrls = this.props.imageUrls === undefined ? [] : this.props.imageUrls;
    this._maxCount = this.props.maxCount === undefined ? 9 : this.props.maxCount;
    this._currentImageDatas = null;
    //当前的图片链接数据
    this._initCurrentImageDatas();

    this._currentLoadingIndex = 0;
    this._itemRefs = [];
    this._isUploading = false;
    this._uploadCallback = null;
  }

  componentWillUpdate(nextProps, nextState) {
    if(nextProps.imageUrls != this.props.imageUrls) {
      // 保存初始化的图片链接数据
      this._customImageUrls = nextProps.imageUrls === undefined ? [] : nextProps.imageUrls;
      this._maxCount = nextProps.maxCount === undefined ? 9 : nextProps.maxCount;
      //当前的图片链接数据
      this._initCurrentImageDatas();
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    if(this._isUploading) {
      return false;
    }
    return true;
  }

  reset() {
    if(this._itemRefs) {
      for (var i = 0; i < this._itemRefs.length; i++) {
        this._itemRefs[i].reset();
      }
      this._currentImageDatas = [];
      this._isUploading = false;
      this._currentLoadingIndex = 0;
    }
  }

  getCurrentImageDatas() {
    return this._currentImageDatas;
  }

  _initCurrentImageDatas() {
    //当前的图片链接数据
    this._currentImageDatas = [];
    let imageData = null;
    for (var i = 0; i < this._customImageUrls.length; i++) {
      imageData = {};
      imageData.type = "server";
      imageData.data = this._customImageUrls[i];
      this._currentImageDatas.push(imageData);
    }
  }

  render() {
    return (
      <View style={this.props.style}>
        <ScrollView style={[{}, this.props.containerStyle]}
            horizontal={true}   // 水平方向
            showsHorizontalScrollIndicator={false}  // 水平指示器
            showsVerticalScrollIndicator={false}    // 垂直指示器
            alwaysBounceHorizontal={false} //弹性拉动一截
          >
          {this._renderCurrentImages()}
          {this._renderEmptyImage()}
        </ScrollView>
      </View>
    )
  }

  _renderCurrentImages() {
    this._itemRefs = [];
    return (
      <View style={{flexDirection:"row"}}>
        {this._currentImageDatas.map(
          (imageData, index) => {
            return this._renderCurrentImageItem(imageData, index);
          }
        )}
      </View>
    )
  }

  _renderCurrentImageItem(imageData, index) {
   
    // console.log("=============", this._itemRefs);
    return (<TImageUpLoadOneComponent imageData={imageData} key={index}
        ref = {
          (ref) => {
            if(ref != null) {
              this._itemRefs.push(ref)
            }
            // console.log(ref);
            // console.log(this._itemRefs);
          }
        }
        imageStyle={this.props.imageStyle}
        style={{marginRight:SizeUtils.translateDesignWidthToCode(20),
          width:SizeUtils.translateDesignWidthToCode(this.props.imageStyle.width),
          height:SizeUtils.translateDesignWidthToCode(this.props.imageStyle.height)}}
        onUpdateCallback={(customImageData, newImageData) => this._onUpdateCallback(customImageData, newImageData)}/>
      )
  }

  _renderEmptyImage() {
    // if(this._currentImageDatas.length >= this._maxCount) {
    //   return;
    // }
    return <TImageUpLoadOneComponent
        imageStyle={this.props.imageStyle} visible={this._currentImageDatas.length < this._maxCount}
        style={{paddingRight:SizeUtils.translateDesignWidthToCode(20),
          width:SizeUtils.translateDesignWidthToCode(this.props.imageStyle.width),
          height:SizeUtils.translateDesignWidthToCode(this.props.imageStyle.height)}}
        onUpdateCallback={(customImageData, newImageData) => this._onUpdateCallback(null, newImageData)}/>
  }

  _onUpdateCallback(customImageData, newImageData) {
    // console.log("_onUpdateCallback", customImageData, newImageData);
    //表示新添加了图片
    if(customImageData === null && newImageData != null) {
      //新添加的图片只能是从本地，所以类型是local
      this._currentImageDatas.push(newImageData);
    }
    //删除
    else if (customImageData != null && newImageData === null) {
      let index = this._currentImageDatas.indexOf(customImageData);
      this._currentImageDatas.splice(index, 1);
    }
    // console.log(this._currentImageDatas);
    this._updateMark();
  }

  checkIsEmpty(){
    return this._currentImageDatas == null || this._currentImageDatas.length <= 0;
  }

  _updateMark() {
    this.setState({
      updateDataMark: this.state.updateDataMark + 1,
    })
    this.props.updateCallback && this.props.updateCallback();
  }

  doUpload(callback) {
    console.log("开始上传所有图片", this._currentImageDatas);
    this._uploadCallback = callback;
    this._currentLoadingIndex = -1;
    this._isUploading = true;
    this._uploadNext();
  }

  _uploadNext() {
    this._currentLoadingIndex += 1;
    if(this._itemRefs.length <= this._currentLoadingIndex) {
      this._loadEnd(true);
    }
    else if(this._currentImageDatas[this._currentLoadingIndex].type === "local"){
      this._itemRefs[this._currentLoadingIndex].doUpload(this._loadOneCallback.bind(this));
    }
    else {
      this._uploadNext();
    }
  }

  _loadOneCallback(result, imageUrl) {
    console.log("单个图片上传回调 ", result, imageUrl, this._currentLoadingIndex);
    if(result) {
      if(imageUrl != null) {
        this._currentImageDatas[this._currentLoadingIndex] = {type:"server", data:imageUrl};
      }
      this._uploadNext();
    }
    else {
      this._loadEnd(false);
    }
  }

  _loadEnd(result) {
    console.log("全部图片上传完毕 ", result);
    this._isUploading = false;
    if(this._uploadCallback && result === true) {
      let imageUrls = [];
      for (var i = 0; i < this._currentImageDatas.length; i++) {
        if(this._currentImageDatas[i].type === "server") {
          imageUrls.push(this._currentImageDatas[i].data);
        }
      }
      console.log("图片地址为", imageUrls);
      this._uploadCallback(imageUrls);
    }
  }
}
